﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BW.Mes.WinForms.Process.OperationModel;
using BW.Mes.WinForms.Process.ProcessModel.Model; // 添加分页管理器引用

namespace BW.Mes.WinForms.Process
{
    public partial class ProcessDataForm : 
   
     DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _processApiBaseUrl = "http://120.26.197.100:8022";
        
        // 添加分页管理器
        private PaginationManager paginationManager;
        // 添加搜索条件变量
        private string searchProcessName = "";
        private string searchProcessCode = "";
        
        public ProcessDataForm()
        {          
            InitializeComponent(); 
            
            // 初始化分页管理器
            paginationManager = new PaginationManager();
            paginationManager.PageChanged += PaginationManager_PageChanged;
            
             // 1. 创建CheckEdit编辑器
            var repositoryItemCheckEdit = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit();
            gridControl1.RepositoryItems.Add(repositoryItemCheckEdit);

            // 2. 创建列，绑定到IsSelected字段
            var gridColumnCheck = new DevExpress.XtraGrid.Columns.GridColumn();
            gridColumnCheck.Caption = "选择";
            gridColumnCheck.Name = "gridColumnCheck";
            gridColumnCheck.FieldName = "IsSelected"; // 修改为绑定到IsSelected字段
            gridColumnCheck.Visible = true;
            gridColumnCheck.VisibleIndex = 0; // 放在第一列
            gridColumnCheck.ColumnEdit = repositoryItemCheckEdit;
            gridColumnCheck.OptionsColumn.AllowEdit = true; // 允许编辑

            // 3. 添加到GridView
            gridView1.Columns.Insert(0, gridColumnCheck);
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            
            // 移除之前的事件订阅（如果有）
            this.Load -= ProcessDataForm_Load;
            // 添加事件订阅
            this.Load += ProcessDataForm_Load;
            
            // 添加查询按钮的事件处理
            this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click);
            
            // 初始化搜索控件
            InitSearchControls();
        }
        
        // 分页事件处理
        private void PaginationManager_PageChanged(object sender, EventArgs e)
        {
            // 页码或页大小改变时重新加载数据
            LoasProcessData().ConfigureAwait(false);
        }
        
        // 添加初始化搜索控件方法
        private void InitSearchControls()
        {
            try
            {
                
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"初始化搜索控件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
      
        
       
        private async void ProcessDataForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 检查是否已有分页面板，有则移除
                Control existingPanel = this.panelControl2.Controls["paginationPanel"];
                if (existingPanel != null)
                {
                    this.panelControl2.Controls.Remove(existingPanel);
                }
                
                // 初始化分页控件
                paginationManager.Initialize(this.panelControl2);
                
                await LoasProcessData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"窗体加载失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task LoasProcessData()
        {
            try
            {
                // 显示加载中提示
                this.Cursor = Cursors.WaitCursor;
                
                // 构建API URL，添加分页参数
                string endpoint = $"T5/ProcessModel/ShowProcess?PagingSize={paginationManager.PageSize}&PagingIndex={paginationManager.CurrentPage}";
                
                // 添加搜索参数
                if (!string.IsNullOrEmpty(searchProcessName))
                {
                    endpoint += $"&ProcessName={Uri.EscapeDataString(searchProcessName)}";
                }
                
                if (!string.IsNullOrEmpty(searchProcessCode))
                {
                    endpoint += $"&ProcessCode={Uri.EscapeDataString(searchProcessCode)}";
                }
                
                // 获取数据
                var process = await GetProcessAsync<List<ProcessModel2>>(endpoint);
                
                // 更新UI
                gridControl1.DataSource = null;
                gridControl1.DataSource = process;
                gridView1.PopulateColumns();
                gridView1.BestFitColumns();
                SetupGridViewColumns();
                gridView1.RefreshData();
                
                // 移到数据加载之后调用，以确保数据加载后立即更新分页信息
                await UpdatePagingInfo();
                
                // 如果数据获取成功但总记录数仍为0，使用当前数据行数作为备用
                if ( process != null && process.Count > 0)
                {
                    // 如果只有一页数据，并且获取的记录数小于页大小，那么总记录数就是当前记录数
                    if (paginationManager.CurrentPage == 1 && process.Count < paginationManager.PageSize)
                    {
                        paginationManager.UpdatePagingData(process.Count);
                    }
                    // 否则，至少有 (当前页-1)*页大小 + 当前获取的记录数
                    else
                    {
                        int estimatedTotal = (paginationManager.CurrentPage - 1) * paginationManager.PageSize + process.Count;
                        paginationManager.UpdatePagingData(estimatedTotal);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        
        // 修改为返回Task的方法
        private async Task UpdatePagingInfo()
        {
            try
            {
                // 获取总记录数
                var countEndpoint = "T5/ProcessModel/GetTotalCount";
                if (!string.IsNullOrEmpty(searchProcessName))
                {
                    countEndpoint += $"?ProcessName={Uri.EscapeDataString(searchProcessName)}";
                    
                    if (!string.IsNullOrEmpty(searchProcessCode))
                    {
                        countEndpoint += $"&ProcessCode={Uri.EscapeDataString(searchProcessCode)}";
                    }
                }
                else if (!string.IsNullOrEmpty(searchProcessCode))
                {
                    countEndpoint += $"?ProcessCode={Uri.EscapeDataString(searchProcessCode)}";
                }
                
                // 清除缓存头，确保获取最新数据
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue
                    {
                        NoCache = true,
                        MustRevalidate = true
                    };
                    
                    client.BaseAddress = new Uri(_processApiBaseUrl);
                    
                    HttpResponseMessage response = await client.GetAsync(countEndpoint);
                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"获取总记录数API响应: {content}");
                        
                        // 尝试直接解析为整数
                        if (int.TryParse(content, out int totalCount))
                        {
                            paginationManager.UpdatePagingData(totalCount);
                            return;
                        }
                        
                        try
                        {
                            // 尝试解析为JSON对象并获取记录数
                            var jsonObj = Newtonsoft.Json.Linq.JObject.Parse(content);
                            
                            // 尝试多种可能的字段名
                            string[] possibleFields = new[] { "totalCount", "TotalCount", "total", "Total", "count", "Count", "recordCount", "RecordCount" };
                            
                            foreach (var field in possibleFields)
                            {
                                if (jsonObj[field] != null)
                                {
                                    totalCount = jsonObj[field].ToObject<int>();
                                    paginationManager.UpdatePagingData(totalCount);
                                    return;
                                }
                            }
                            
                            // 尝试从数据结构中获取
                            if (jsonObj["data"] != null && jsonObj["data"].Type == Newtonsoft.Json.Linq.JTokenType.Array)
                            {
                                var dataArray = jsonObj["data"].ToObject<object[]>();
                                if (dataArray != null)
                                {
                                    paginationManager.UpdatePagingData(dataArray.Length);
                                    return;
                                }
                            }
                            
                            // 尝试查找带有totalXXX格式的任何字段
                            foreach (var prop in jsonObj.Properties())
                            {
                                if (prop.Name.ToLower().Contains("total") && int.TryParse(prop.Value.ToString(), out totalCount))
                                {
                                    paginationManager.UpdatePagingData(totalCount);
                                    return;
                                }
                            }
                        }
                        catch (Exception jsonEx)
                        {
                            Console.WriteLine($"解析总记录数JSON失败: {jsonEx.Message}");
                        }
                    }
                }
                
                // 如果通过API获取总记录数失败，尝试从当前数据网格中获取
                try
                {
                    if (gridView1.RowCount > 0)
                    {
                        int currentPageRowCount = gridView1.RowCount;
                        
                        // 如果当前页数据量小于每页大小，且是第一页，那么总数就是当前行数
                        if (currentPageRowCount < paginationManager.PageSize && paginationManager.CurrentPage == 1)
                        {
                            paginationManager.UpdatePagingData(currentPageRowCount);
                        }
                        // 否则，总数至少是 (当前页码-1)*页大小 + 当前页行数
                        else if (paginationManager.CurrentPage > 0)
                        {
                            int estimatedTotal = (paginationManager.CurrentPage - 1) * paginationManager.PageSize + currentPageRowCount;
                            paginationManager.UpdatePagingData(estimatedTotal);
                        }
                    }
                }
                catch (Exception gridEx)
                {
                    Console.WriteLine($"从网格获取记录数失败: {gridEx.Message}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新分页信息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 设置网格视图列的显示格式，特别是ProcessadEnable列
        /// </summary>
        private void SetupGridViewColumns()
        {
            // 确保gridView1已经绑定了数据源并创建了列
            if (gridView1.Columns["ProcessadEnable"] != null)
            {
                // 获取ProcessadEnable列
                DevExpress.XtraGrid.Columns.GridColumn enableColumn = gridView1.Columns["ProcessadEnable"];

                // 设置列标题
                enableColumn.Caption = "状态";

                // 创建下拉列表编辑器以替换复选框
                DevExpress.XtraEditors.Repository.RepositoryItemComboBox riCombo =
                    new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
                riCombo.Items.AddRange(new object[] { "禁用", "启用" });

                // 将列的编辑器改为下拉列表
                gridControl1.RepositoryItems.Add(riCombo);
                enableColumn.ColumnEdit = riCombo;

                // 设置为只读，不允许用户编辑
                enableColumn.OptionsColumn.AllowEdit = false;

                // 注册自定义显示文本事件
                gridView1.CustomColumnDisplayText -= GridView1_CustomColumnDisplayText;
                gridView1.CustomColumnDisplayText += GridView1_CustomColumnDisplayText;
            }
            
            // 确保IsSelected列可编辑
            if (gridView1.Columns["IsSelected"] != null)
            {
                gridView1.Columns["IsSelected"].OptionsColumn.AllowEdit = true;
            }
        }

        /// <summary>
        /// 自定义列显示文本事件处理
        /// </summary>
        private void GridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            // 仅处理ProcessadEnable列
            if (e.Column.FieldName == "ProcessadEnable" && e.Value != null)
            {
                bool isEnabled = Convert.ToBoolean(e.Value);
                e.DisplayText = isEnabled ? "启用" : "禁用";
            }
        }
        private async Task<T> GetProcessAsync<T>(string endpoint)
       {
            HttpResponseMessage repoonse=await _httpClient.GetAsync($"{_processApiBaseUrl}/{endpoint}");
            repoonse.EnsureSuccessStatusCode();
            string responseBody = await repoonse.Content.ReadAsStringAsync();

            Console.WriteLine($"API响应:{responseBody}");
            var josnobject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

            // 尝试从不同的字段获取数据
            if (josnobject["pagingdata"] != null)
            {
                string dataJson = josnobject["pagingdata"].ToString();
                Console.WriteLine($"提取的pagingdata字段:{dataJson}");
                return JsonConvert.DeserializeObject<T>(dataJson);
            }
            else if (josnobject["pagingData"] != null)
            {
                string dataJson = josnobject["pagingData"].ToString();
                Console.WriteLine($"提取的pagingData字段:{dataJson}");
                return JsonConvert.DeserializeObject<T>(dataJson);
            }
            else if (josnobject["data"] != null)
            {
                string dataJson = josnobject["data"].ToString();
                Console.WriteLine($"提取的data字段:{dataJson}");
                return JsonConvert.DeserializeObject<T>(dataJson);
            }

            return JsonConvert.DeserializeObject<T>(responseBody);
       }

        /// <summary>
        /// 编辑按钮点击事件
        /// </summary>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            LoasProcessData();
        }

        /// <summary>
        /// 添加按钮点击事件
        /// </summary>
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            // 创建添加窗体
            var addForm = new AddProcessForm();
            
            // 订阅ProcessAdded事件
            addForm.ProcessAdded += AddForm_ProcessAdded;
            
            // 显示对话框，以模态方式打开
            addForm.ShowDialog();
        }
        
        // 添加事件处理方法
        private async void AddForm_ProcessAdded(object sender, EventArgs e)
        {
            // 当添加操作完成后刷新数据
            await LoasProcessData();
        }

        /// <summary>
        /// 批量删除方法
        /// </summary>
        private async void simpleButton4_Click (object sender, EventArgs e)
        {
            var checkedIds = new List<long>();
            for (int rowHandle = 0; rowHandle < gridView1.RowCount; rowHandle++)
            {
                bool isChecked = false;
                var val = gridView1.GetRowCellValue(rowHandle, "IsSelected");
                if (val != null && val is bool)
                    isChecked = (bool)val;
                if (!isChecked) continue;
                var idObj = gridView1.GetRowCellValue(rowHandle, "Id");
                if (idObj == null) continue;
                long id = Convert.ToInt64(idObj);
                checkedIds.Add(id);
            }
            if (checkedIds.Count == 0)
            {
                XtraMessageBox.Show("请先勾选要删除的行！");
                return;
            }
            if (XtraMessageBox.Show($"确认删除选中的 {checkedIds.Count} 条记录？", "批量删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;
            using (var client = new HttpClient { BaseAddress = new Uri(_processApiBaseUrl) })
            {
                foreach (var id in checkedIds)
                {
                    var resp = await client.DeleteAsync($"/T5/ProcessModel/DeleteProcessModel?Id={id}");
                    if (!resp.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show($"删除 Id={id} 失败：{resp.ReasonPhrase}");
                        return;
                    }
                }
            }
            await LoasProcessData();
            XtraMessageBox.Show("删除完成！");
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            // 获取选中的行
            var selectedRow = gridView1.GetFocusedRow() as ProcessModel2;
            if (selectedRow != null)
            {
                // 打开编辑窗体
                var updateForm = new ProcessUpdateForm(selectedRow);
                
                // 订阅ProcessUpdated事件
                updateForm.ProcessUpdated += UpdateForm_ProcessUpdated;

                updateForm.ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("请先选择一条记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        
        // 添加事件处理方法
        private async void UpdateForm_ProcessUpdated(object sender, EventArgs e)
        {
            // 当更新操作完成后刷新数据
            await LoasProcessData();
        }

        /// <summary>
        /// 查询按钮点击事件
        /// </summary>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 从界面获取查询条件
                searchProcessName = textEdit1.Text.Trim();
                
                // 重置到第一页
                paginationManager.SetCurrentPage(1);
                
                // 执行查询
                LoasProcessData().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}